<!DOCTYPE html>
<html>

  <head>
    <script src="../dist/svg-pan-zoom.js"></script>
    <script src="jquery.min.js"></script>
  </head>

  <body>
    <h1>Demo for svg-pan-zoom: Dynamic SVG load</h1>
    <div id="container"></div>
    <button id="swap" style="padding: 5px 20px; background: red; border: 1px solid #ff0404;">swap</button>

    <script>
      // Don't use window.onLoad like this in production, because it can only listen to one function.
      $(function() {
        var lastEventListener = null;

        function createNewEmbed(src){
          var embed = document.createElement('embed');
          embed.setAttribute('style', 'width: 500px; height: 500px; border:1px solid black;');
          embed.setAttribute('type', 'image/svg+xml');
          embed.setAttribute('src', src);

          document.getElementById('container').appendChild(embed)

          lastEventListener = function(){
            svgPanZoom(embed, {
              zoomEnabled: true,
              controlIconsEnabled: true
            });
          }
          embed.addEventListener('load', lastEventListener)

          return embed
        }

        var lastEmbedSrc = 'tiger.svg'
          , lastEmbed = createNewEmbed(lastEmbedSrc)
          ;

        function removeEmbed(){
          // Destroy svgpanzoom
          svgPanZoom(lastEmbed).destroy()
          // Remove event listener
          lastEmbed.removeEventListener('load', lastEventListener)
          // Null last event listener
          lastEventListener = null
          // Remove embed element
          document.getElementById('container').removeChild(lastEmbed)
          // Null reference to embed
          lastEmbed = null
        }


        $('#swap').on('click', function(){
          // Remove last added svg
          removeEmbed()

          if (lastEmbedSrc == 'tiger.svg') {
            lastEmbedSrc = 'Tux.svg'
          } else {
            lastEmbedSrc = 'tiger.svg'
          }

          lastEmbed = createNewEmbed(lastEmbedSrc)
        })
      });
    </script>

  </body>

</html>
